package com.example.contactfragment;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.boyuan.huijiaoyu.AddGroup;
import com.boyuan.huijiaoyu.DeleGroup;
import com.boyuan.huijiaoyu.DeleMember;
import com.boyuan.huijiaoyu.Group;
import com.boyuan.huijiaoyu.GroupAddMember;
import com.boyuan.huijiaoyu.Huodong;
import com.boyuan.huijiaoyu.R;
import com.example.login.LoginApp1;
import com.example.newfragment.DetailPerson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.magicsoft.app.entity.GroupForCaseIdEntity;
import com.magicsoft.app.helper.DateUtils;
import com.magicsoft.app.helper.TokenHelper;
import com.magicsoft.app.wcf.AsyncHttpServiceHelper;
import com.magicsoft.app.wcf.BaseService;
import com.magicsoft.app.wcf.listener.GetMultilParamsListener;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.magicsoft.app.wcf.listener.PostRecordResponseListener;
import com.magicsoft.constant.Constant;
import com.ttcaca.cas.android.client.utils.Encoder;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.session.MediaSession.Token;
import android.os.IBinder;
import android.util.Log;

public class ContactGroupService extends BaseService {

	public static String appID = "ICEHJY00-3A88-4E17-BC84-5A2DB101B226";
	public static String token = "BXPHrDC8ARa8xYVkgV5c";

	public ContactGroupService(Context context) {
		super(context);
	}

	/*
	 * 通过CaseID获取群组详情
	 */
	public void getGroupByCaseId(String caseID,
			final GetOneRecordListener<List<GroupForCaseIdEntity>> listener) {
		String getParamString = "";
		try {
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String requestUrl = Constant.IM_GROUP + getParamString + "&caseID="
				+ caseID;
		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					String code = response.getString("code");
					if ("0".equals(code)) {
						JSONArray content = response.getJSONArray("content");
						Type type = new TypeToken<List<GroupForCaseIdEntity>>() {
						}.getType();
						List<GroupForCaseIdEntity> myGroups = gson.fromJson(
								content.toString(), type);
						if (listener != null) {
							listener.onFinish(myGroups);
						}
					} else {
						String message = response.getString("message");
						if (listener != null) {
							listener.onFailed(message);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				super.onFailure(statusCode, headers, throwable, errorResponse);
			}
		});

	}
	
	//用群组id获取群组详情
	public void getIdGroupname(String groupID, final GetOneRecordListener<List<GroupName>> listener){
		String requestUrl = "";
		String getParamString = "";
		
		try {
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		requestUrl = Constant.CONTACT_MYGROUP + getParamString + "id=" + groupID;
		
		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					String code = response.getString("code");
					String message = response.getString("message");
					if ("0".equals(code)) {
						JSONArray contentArray = response.getJSONArray("content");
						List<GroupName> result = new ArrayList<GroupName>();
						if (contentArray.toString().length() > 5) {

							Type contentType = new TypeToken<List<GroupName>>() {
							}.getType();
							List<GroupName> datas = gson.fromJson(
									contentArray.toString(), contentType);
							result.addAll(datas);
						}
						if (listener != null) {
							listener.onFinish(result);
						}
					}else{
						if (listener != null){
							listener.onFailed(message);
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				super.onFailure(statusCode, headers, throwable, errorResponse);
			}
		});
	}

	/**
	 * 获取我的群组
	 * 
	 */

	public void getMygroup(String name,
			final GetOneRecordListener<List<MyGroup>> listener) {
		String requestUrl = "";
		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (Exception e) {
		}

		requestUrl = Constant.CONTACT_MYGROUP + getParamString + "&username="
				+ name;
		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					String code = response.getString("code");
					String message = response.getString("message");
					if ("0".equals(code)) {
						JSONArray contentArray = response
								.getJSONArray("content");

						List<MyGroup> result = new ArrayList<MyGroup>();
						if (contentArray.toString().length() > 5) {

							Type contentType = new TypeToken<List<MyGroup>>() {
							}.getType();
							List<MyGroup> datas = gson.fromJson(
									contentArray.toString(), contentType);
							Log.e("data", datas.toString());
							result.addAll(datas);
						}
						if (listener != null) {
							listener.onFinish(result);
						}
					} else {
						if (listener != null)
							listener.onFailed(message);
					}

				} catch (Exception e) {

					if (listener != null)
						listener.onFailed(context.getResources().getString(// JSON
								// 解析错误
								R.string.json_analysis_wrong));
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {

				super.onFailure(statusCode, headers, responseString, throwable);
				if (listener != null)
					listener.onFailed(context.getResources().getString(
							R.string.network_connections_wrong));

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, throwable, errorResponse);
				if (listener != null)
					listener.onFailed(context.getResources().getString(
							R.string.network_connections_wrong));
			}
		});

	}
	
	//获取我的普通群组
	public void getMynormalgroup(String name, final GetOneRecordListener<List<MyGroup>> listener){
		String requestUrl = "";
		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (Exception e) {
		}

		requestUrl = Constant.CONTACT_MYGROUP + getParamString + "&username="
				+ name+"&type=normal";
		
		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					String code = response.getString("code");
					String message = response.getString("message");
					if("0".equals(code)){
//						JSONObject jsonObject = response.getJSONObject("content");
//						Iterator<String> keys = jsonObject.keys();
//						List<MyGroup> groupList = new ArrayList<MyGroup>();
//						while(keys.hasNext()){
//							JSONObject jsonObject2 = jsonObject.getJSONObject(keys.next());
//							Type contentType = new TypeToken<MyGroup>() {
//							}.getType();
//							MyGroup group = gson.fromJson(jsonObject2.toString(), contentType);
//							groupList.add(group);
//						}
						
						JSONArray contentArray = response.getJSONArray("content");

						List<MyGroup> result = new ArrayList<MyGroup>();
						if (contentArray.toString().length() > 5) {

							Type contentType = new TypeToken<List<MyGroup>>() {
							}.getType();
							List<MyGroup> datas = gson.fromJson(
									contentArray.toString(), contentType);
							result.addAll(datas);
						}
						if(listener != null){
							listener.onFinish(result);
						}
					}else{
						if(listener != null){
							listener.onFailed(message);
						}
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, throwable, errorResponse);
			}
		});
	}
	
	//获取我的case群组
		public void getMycasegroup(String name, final GetOneRecordListener<List<MyGroup>> listener){
			String requestUrl = "";
			String getParamString = "";

			try {//
				getParamString = TokenHelper.FetchColourToken(context, false);
			} catch (Exception e) {
			}

			requestUrl = Constant.CONTACT_MYGROUP + getParamString + "&username="
					+ name+"&type=case";
			AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler(){
				@Override
				public void onSuccess(int statusCode, Header[] headers,
						JSONObject response) {
					super.onSuccess(statusCode, headers, response);
					try {
						String code = response.getString("code");
						String message = response.getString("message");
						if("0".equals(code)){
							JSONArray contentArray = response
									.getJSONArray("content");

							List<MyGroup> result = new ArrayList<MyGroup>();
							if (contentArray.toString().length() > 5) {

								Type contentType = new TypeToken<List<MyGroup>>() {
								}.getType();
								List<MyGroup> datas = gson.fromJson(
										contentArray.toString(), contentType);
								result.addAll(datas);
							}
							if(listener != null){
								listener.onFinish(result);
							}
						}else{
							if(listener != null){
								listener.onFailed(message);
							}
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				@Override
				public void onFailure(int statusCode, Header[] headers,
						Throwable throwable, JSONObject errorResponse) {
					// TODO Auto-generated method stub
					super.onFailure(statusCode, headers, throwable, errorResponse);
				}
			});
		}
	

	/**
	 * 获取群组成员
	 * 
	 */

	public void getGroupMember(String groupId,
			final GetOneRecordListener<List<GroupMember>> listener) {

		String getParamString = "";

		try {//
			getParamString = TokenHelper.FetchColourToken(context, false);
		} catch (Exception e) {
		}

		String requestUrl = Constant.CONTACT_GROUPMEMBER + "?id=" + groupId
				+ "&sign=15bd2e58a0af5115cfff5d56de7aa851&ts=1433840364&appID="
				+ TokenHelper.appID;

		AsyncHttpServiceHelper.get(requestUrl, new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {

					String code = response.getString("code");
					String message = response.getString("message");
					if ("0".equals(code)) {
						JSONArray contentArray = response
								.getJSONArray("content");

						List<GroupMember> result = new ArrayList<GroupMember>();
						if (contentArray.toString().length() > 5) {

							Type contentType = new TypeToken<List<GroupMember>>() {
							}.getType();
							List<GroupMember> datas = gson.fromJson(
									contentArray.toString(), contentType);

							result.addAll(datas);
						}

						if (listener != null) {
							listener.onFinish(result);
						}
					} else {
						if (listener != null)
							listener.onFailed(message);
					}

				} catch (Exception e) {

					if (listener != null)
						listener.onFailed(context.getResources().getString(// JSON
								// 解析错误
								R.string.json_analysis_wrong));
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {

				super.onFailure(statusCode, headers, responseString, throwable);
				if (listener != null)
					listener.onFailed(context.getResources().getString(
							R.string.network_connections_wrong));

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				// TODO Auto-generated method stub
				super.onFailure(statusCode, headers, throwable, errorResponse);
				if (listener != null)
					listener.onFailed(context.getResources().getString(
							R.string.network_connections_wrong));
			}
		});

	}

	/**
	 * 删除群组成员
	 * 
	 */

	public void delGroupMember(final String size, String id, String usernames,
			final GetOneRecordListener<List<DeleMember>> listener,
			final GetMultilParamsListener listener1) {
		long ts = DateUtils.getCurrentDate();

		String sign;
		try {
			sign = getToken(ts + "");
			String url = Constant.BaseUrl + "im/group/member?"
					+ "id=" + id + "&usernames=" + usernames + "&sign=" + sign
					+ "&ts=" + ts + "&appID=" + appID;
			AsyncHttpServiceHelper.delete(url, new JsonHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, Header[] headers,
						JSONObject response) {
					super.onSuccess(statusCode, headers, response);
					try {
						String code = response.getString("code");
						if ("0".equals(code)) {
							if ("1".equals(size)) {
								JSONObject content1 = response
										.getJSONObject("content");
								Type contentType = new TypeToken<DeleMember>() {
								}.getType();
								DeleMember deleMembers = gson.fromJson(
										content1.toString(), contentType);
								if (listener1 != null) {
									listener1.onFinish(deleMembers);
								}
							} else {
								JSONArray content = response
										.getJSONArray("content");
								Type contentType = new TypeToken<List<DeleMember>>() {
								}.getType();
								List<DeleMember> deleMembers = gson.fromJson(
										content.toString(), contentType);
								if (listener != null) {
									listener.onFinish(deleMembers);
								}
							}
						} else {
							if (listener != null) {
								String message = response.getString("message");
								listener.onFailed(message);
							}

						}

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onFailure(int statusCode, Header[] headers,
						Throwable throwable, JSONArray errorResponse) {
					super.onFailure(statusCode, headers, throwable,
							errorResponse);
				}
			});
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 删除群组
	 * 
	 */

	public void delGroup(String id, final GetMultilParamsListener listener) {
		long ts = DateUtils.getCurrentDate();

		String sign;
		try {
			sign = getToken(ts + "");
			String url = Constant.BaseUrl + "im/group?" + "id=" + id
					+ "&sign=" + sign + "&ts=" + ts + "&appID=" + appID;
			AsyncHttpServiceHelper.delete(url, new JsonHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, Header[] headers,
						JSONObject response) {
					// TODO Auto-generated method stub
					super.onSuccess(statusCode, headers, response);
					try {

						String code = response.getString("code");
						String message = response.getString("message");
						if ("0".equals(code)) {
							JSONObject content = response
									.getJSONObject("content");
							Type contentType = new TypeToken<DeleGroup>() {
							}.getType();
							DeleGroup group = gson.fromJson(content.toString(),
									contentType);
							if (listener != null) {
								listener.onFinish(group);
							}
						} else {
							if (listener != null)
								listener.onFailed(message);
						}

					} catch (Exception e) {

						if (listener != null)
							listener.onFailed(context.getResources().getString(// JSON
																				// 解析错误
									R.string.json_analysis_wrong));
					}
				}

				@Override
				public void onFailure(int statusCode, Header[] headers,
						Throwable throwable, JSONObject errorResponse) {
					// TODO Auto-generated method stub
					super.onFailure(statusCode, headers, throwable,
							errorResponse);
				}
			});
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String getToken(String ts)
			throws UnsupportedEncodingException, NoSuchAlgorithmException {

		String result = Encoder.md5(appID + ts + token + false);

		result = Encoder.urlEncode(result);

		return result;
	}

	// 新建群组
	public void newGroup(String owner, String groupname, String desc,
			boolean approval, String maxusers, String members,
			final GetMultilParamsListener listener) {

		String requestUrl = Constant.NEWGROUP;
		RequestParams params = new RequestParams();

		try {//
			params = TokenHelper.FetchColourToken5(context, true, owner,
					groupname, desc, approval, maxusers, members);
		} catch (Exception e) {
		}

		AsyncHttpServiceHelper.post(requestUrl, params,
				new JsonHttpResponseHandler() {
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						super.onSuccess(statusCode, headers, response);
						try {
							String code = response.getString("code");
							String message = response.getString("message");
							if ("0".equals(code)) {
								JSONObject content = response
										.getJSONObject("content");
								Type contentType = new TypeToken<AddGroup>() {
								}.getType();
								AddGroup group = gson.fromJson(
										content.toString(), contentType);
								if (listener != null) {
									listener.onFinish(group);
								}
							} else {
								if (listener != null)
									listener.onFailed(message);
							}

						} catch (Exception e) {
							if (listener != null)
								listener.onFailed(context.getResources()
										.getString(// JSON
													// 解析错误
												R.string.json_analysis_wrong));
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONObject errorResponse) {
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
						if (listener != null)
							listener.onFailed(context.getResources().getString(
									R.string.network_connections_wrong));
					}
				});
	}

	// 群组加人
	public void addcontacts(String groupid, String usernames,
			final GetMultilParamsListener listener) {

		String requestUrl = Constant.ADDCONTACTTOGROUP;
		RequestParams params = new RequestParams();

		try {//
			params = TokenHelper.FetchColourToken7(context, true, groupid,
					usernames);
		} catch (Exception e) {
		}
		AsyncHttpServiceHelper.post(requestUrl, params,
				new JsonHttpResponseHandler() {
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						super.onSuccess(statusCode, headers, response);
						try {
							String code = response.getString("code");
							String message = response.getString("message");
							if ("0".equals(code)) {
								JSONObject content = response
										.getJSONObject("content");
								Type contentType = new TypeToken<GroupAddMember>() {
								}.getType();
								GroupAddMember group = gson.fromJson(
										content.toString(), contentType);
								if (listener != null) {
									listener.onFinish(group);
								}
							} else {
								if (listener != null)
									listener.onFailed(message);
							}

						} catch (Exception e) {
							if (listener != null)
								listener.onFailed(context.getResources()
										.getString(// JSON
													// 解析错误
												R.string.json_analysis_wrong));
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							Throwable throwable, JSONObject errorResponse) {
						Log.e("errorResponse", "errorResponse=" + errorResponse);
						super.onFailure(statusCode, headers, throwable,
								errorResponse);
						if (listener != null)
							listener.onFailed(context.getResources().getString(
									R.string.network_connections_wrong));
					}
				});
	}

	// 通过账号获取用户信息
	public void getuUserid(String username,
			final GetMultilParamsListener listener) {
		String url1 = Constant.GETUSERID;
		String params = "";
		try {
			params = TokenHelper.FetchColourToken_getuserid(context, true,
					username);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String url = url1 + params;
		AsyncHttpServiceHelper.get(url, new JsonHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					String code = response.getString("code");
					String message = response.getString("message");
					Log.e("code", code);
					if ("0".equals(code)) {
						JSONObject content = response.getJSONObject("content");
						Type contentType = new TypeToken<LognUser>() {
						}.getType();
						LognUser user = gson.fromJson(content.toString(),
								contentType);
						Log.e("user", user.toString());
						if (listener != null) {
							listener.onFinish(user);
						}
					} else {
						if (listener != null) {
							listener.onFailed(message);
						}
					}
				} catch (JSONException e) {
					Log.e("ContactGroup", "message =" + e.getMessage());
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				Log.e("JSONObject", errorResponse.toString());
				super.onFailure(statusCode, headers, throwable, errorResponse);
			}
			
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONArray errorResponse) {
				Log.e("JSONArray", errorResponse.toString());
				super.onFailure(statusCode, headers, throwable, errorResponse);
			}
		});
		
		
	}

	// 修改群组名称
	public void changeGN(String id, String groupname,
			final PostRecordResponseListener listener) {
		String url = Constant.CHANGEGROUPNAME;
		RequestParams params = new RequestParams();
		try {
			params = TokenHelper.FetchColourToken_changegroupname(context,
					true, id, groupname, "123", "200");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		AsyncHttpServiceHelper.put(url, params, new JsonHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					String code = response.getString("code");
					String message = response.getString("message");
					if ("0".equals(code)) {
						if (listener != null) {
							listener.onFinish(message);
						}
					} else {
						if (listener != null) {
							listener.onFailed(message);
						}
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, JSONObject errorResponse) {
				super.onFailure(statusCode, headers, throwable, errorResponse);

			}
		});
	}

}
